﻿/* 2012/12/27 */
using System;
using System.Collections.Generic;
using System.Text;

namespace Cosmos.Collections.Generic
{
    public class DictionaryDuplicateList<TKey, TValue> : IDuplicateList<TKey, TValue>
    {
        private Dictionary<TKey, LinkedList<TValue>> _dictionary;

        public DictionaryDuplicateList()
        {
            _dictionary = new Dictionary<TKey, LinkedList<TValue>>();
        }

        public bool Contains(TKey key)
        {
            return _dictionary.ContainsKey(key);
        }

        public void Clear()
        {
            _dictionary.Clear();
        }

        public void Add(TKey key)
        {
            if (!_dictionary.ContainsKey(key))
            {
                _dictionary.Add(key, new LinkedList<TValue>());
            }
        }

        public void Add(TKey key, TValue value)
        {
            if (_dictionary.ContainsKey(key))
            {
                _dictionary[key].AddLast(value);
            }
            else
            {
                LinkedList<TValue> list = new LinkedList<TValue>();
                list.AddLast(value);
                _dictionary.Add(key, list);
            }
        }

        public void Remove(TKey key)
        {
            if (_dictionary.ContainsKey(key))
            {
                _dictionary.Remove(key);
            }
        }

        public void Remove(TKey key, TValue value)
        {
            if (_dictionary.ContainsKey(key))
            {
                LinkedList<TValue> list = _dictionary[key];
                list.Remove(value);
                if (list.Count == 0)
                {
                    _dictionary.Remove(key);
                }
            }
        }

        public void RemoveExcept(TKey key, TValue value)
        {
            if (_dictionary.ContainsKey(key))
            {
                LinkedList<TValue> list = _dictionary[key];
                if (list.Contains(value))
                {
                    list.Clear();
                    list.AddLast(value);
                }
            }
        }

        public bool TryGetValues(TKey key, out TValue[] values)
        {
            if (_dictionary.ContainsKey(key))
            {
                LinkedList<TValue> list = _dictionary[key];
                values = new TValue[list.Count];
                list.CopyTo(values, 0);
                return true;
            }
            else
            {
                values = null;
                return false;
            }
        }
    }
}
